<template>
  <!-- 在页面顶部或底部添加加载遮罩 -->
  <div v-loading="submitting" class="inventory-sheet-detail-container">
    <div class="inventory-sheet-detail-container">
      <!-- Document Information Group -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <div class="title-wrapper">
              <span class="title-text">单据信息</span>
              <span class="store-name">{{ inventorySheet.storeName }}</span>
              <el-tag v-if="!this.editMode"
                :type="inventorySheet.status.code === CommonOrderStatus.Passed.code ? 'success' : 'info'" size="small"
                class="status-tag">
                {{ inventorySheet.status.name }}
              </el-tag>
            </div>
            <!-- Action Buttons -->
            <div class="action-buttons" v-if="!this.editMode">
              <el-button plain @click="handleCopy">
                <el-icon>
                  <CopyDocument />
                </el-icon> 复制
              </el-button>
              <el-button plain @click="handlePrint" style="margin-right: 20px">
                <el-icon>
                  <Printer />
                </el-icon> 打印
              </el-button>
              <!--  暂时不提供编辑功能
              <el-button type="primary" plain @click="handleEdit">
                <el-icon>
                  <Edit />
                </el-icon> 编辑
              </el-button>
              <el-button type="danger" plain @click="handleDelete">
                <el-icon>
                  <Delete />
                </el-icon> 删除
              </el-button>
              --->
            </div>
          </div>
        </template>
        <el-form ref="ruleFormRef" :model="formData" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="6">
              <input-widget-web v-model="formData.title" label="单据标题" prop="title" :readonly="!this.editMode" />
            </el-col>
            <el-col v-if="!this.editMode" :span="6">
              <input-widget-web v-model="formData.docCode" label="单据编号" prop="docCode" :readonly="!this.editMode" />
            </el-col>

            <el-col :span="6">
              <warehouse-select v-model="formData.warehouse" label="仓库" prop="warehouse" :readonly="!this.editMode"
                :inventoryUiAction="inventoryUiAction" />
            </el-col>

            <el-col :span="6">
              <date-time-select v-model="formData.operateDate" label="盘点日期" prop="operateDate"
                :readonly="!this.editMode" type="datetime" />
            </el-col>

            <el-col :span="6">
              <employee-select v-model="formData.operator" label="经办人" prop="operator" :readonly="!this.editMode"
                :enterpriseMgtUiAction="enterpriseMgtUiAction" />
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- Inventory Items Group -->
      <el-card class="items-card" shadow="never">
        <template #header>
          <div class="card-header">
            <div class="title-wrapper">
              <div class="summary-container">
                <span class="title-text">盘点商品</span>
                <span class="total-info">
                  共{{ inventorySheet.commodityList.length }}件商品
                </span>
              </div>
              <!-- 添加和删除按钮 -->
              <div v-if="editMode" class="action-buttons">
                <el-button type="primary" size="small" @click="handleAddCommodity">
                  添加商品
                </el-button>
                <el-button type="danger" size="small" @click="handleDeleteSelectedCommodities">
                  删除商品
                </el-button>
              </div>
            </div>
          </div>
        </template>

        <el-table :data="inventorySheet.commodityList" style="width: 100%" @selection-change="handleSelectionChange">
          <!-- 勾选列 -->
          <el-table-column type="selection" width="55" v-if="editMode" />
          <el-table-column label="图片" width="150">
            <template #default="scope">
              <el-image v-if="scope.row.commodity.imgs" :src="scope.row.commodity.imgs.split(',')[0]" fit="cover"
                class="commodity-image"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="180">
            <template #default="scope">
              {{ scope.row.commodity.name }}
            </template>
          </el-table-column>
          <el-table-column label="规格" width="180">
            <template #default="scope">
              {{ scope.row.commodity.standard }}
            </template>
          </el-table-column>
          <el-table-column label="单位" width="80">
            <template #default="scope">
              {{ scope.row.commodity.unit?.name || '-' }}
            </template>
          </el-table-column>

          <el-table-column label="库存数量" align="right" width="100">
            <template #default="scope">
              <span>{{ formatCount(scope.row.count.value) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="盘点数量" align="right" width="100">
            <template #default="scope">
              <adjust-count-input-cell v-if="editMode" :commodityBatchSheet="scope.row" :decimalAllowed="true" />
              <span v-else>{{ scope.row.adjustCount ? formatCount(scope.row.adjustCount.value) : '-' }}</span>
            </template>
          </el-table-column>

          <el-table-column label="盈亏数量" align="right" width="100">
            <template #default="scope">
              <span :class="getAdjustBalanceClass(scope.row.adjustBalance.value)">
                {{ formatCount(scope.row.adjustBalance.value, true) }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- Other Information Group -->
      <el-card class="other-info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <div class="title-wrapper">
              <span class="title-text">其他信息</span>
            </div>
          </div>
        </template>

        <el-descriptions v-if="!editMode" :column="1">
          <el-descriptions-item v-if="latestUpdateInfo" label="最近更新">{{ latestUpdateInfo
          }}</el-descriptions-item>
          <el-descriptions-item label="制单人">{{ docMaker }}</el-descriptions-item>
          <el-descriptions-item label="备注">
            <div class="remark-content">{{ inventorySheet.remark || '-' }}</div>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 备注 -->
        <input-widget-web v-if="editMode" v-model="formData.remark" label="备注" prop="remark" placeholder="请输入备注信息"
          :remarkMode="true" />
      </el-card>

      <!-- 底部操作栏 (仅在编辑模式下显示) -->
      <bottom-bar :visible="editMode">
        <template #left>
          <span class="doc-maker-info">制单人: {{ docMakerBottmBar }}</span>
        </template>
        <template #right>
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </template>
      </bottom-bar>

      <!-- 商品选择弹窗 -->
      <subcommodity-select-dialog ref="commoditySelectDialog" :basic-ui-action="basicUiAction"
        @select="handleCommoditySelect" />
    </div>
  </div>
</template>

<script>
import { InventorySheet, CommodityBatchSheet } from '../../public/engine/inventory/inventorySheet'
import { Employee } from '../../public/engine/enterpriseMgt/employee'
import { CsDouble } from '../../public/engine/common/csDouble'
import { CommonOrderStatus } from '../../public/engine/common/docDefinition'
import { InventoryUiAction } from '../../public/engine/uiAction/inventoryUiAction'
import { Util } from '../../public/utils/util'
import { DateUtil } from '../../public/utils/dateUtil'
import { Engine } from '../../public/engine/engine'
import { ElMessage, ElMessageBox } from 'element-plus'
import { BasicUiAction } from '../../public/engine/uiAction/basicUiAction'
import { EnterpriseMgtUiAction } from '../../public/engine/uiAction/enterpriseMgtUiAction.js'
import { ActionResult, ActionResultType } from '../../public/engine/common/actionResult.js'
import InputWidgetWeb from '../../public/views/componentsWeb/InputWidgetWeb.vue'
import WarehouseSelect from '../../public/views/componentsWeb/WarehouseSelect.vue'
import DateTimeSelect from '../../public/views/componentsWeb/DateTimeSelect.vue'
import EmployeeSelect from '../../public/views/componentsWeb/EmployeeSelect.vue'
import AdjustCountInputCell from '../../public/views/componentsWeb/AdjustCountInputCell.vue'
import QualityInputCell from '../../public/views/componentsWeb/QualityInputCell.vue'
import SubcommoditySelectDialog from '../../views/inventory/subcommoditySelectDialog.vue'
import BottomBar from '../../public/views/componentsWeb/BottomBar.vue'
import EventBus from '../../public/engine/ipc/eventBus'
import TabUtil from '@/plugins/tab'
import { MessageUtil } from '@/utils/MessageUtil'

export default {
  name: 'sheet',
  components: {
    InputWidgetWeb,
    WarehouseSelect,
    DateTimeSelect,
    EmployeeSelect,
    AdjustCountInputCell,
    SubcommoditySelectDialog,
    BottomBar,
    QualityInputCell
  },

  data() {
    return {
      inventorySheet: InventorySheet.empty({
        operator: Engine.profile?.nickName,
        operatorId: Engine.profile?.id
      }),
      orgInventorySheet: InventorySheet.empty({
        operator: Engine.profile?.nickName,
        operatorId: Engine.profile?.id
      }),
      basicUiAction: new BasicUiAction(),
      inventoryUiAction: new InventoryUiAction(),
      enterpriseMgtUiAction: new EnterpriseMgtUiAction(),
      loading: false,
      CommonOrderStatus,
      editMode: false,
      orderId: "",
      formData: {
        docCode: '',
        title: '',
        warehouse: null,
        operateDate: null,
        operator: null,
        remark: '',
        updator: null,
        docMaker: null,
      },
      // 返回数据
      retValue: null,
      selectedCommodities: [],
      submitting: false, // 添加提交状态标识
    }
  },

  mounted() {
    this.retValue = null;
    this.orderId = (this.$route.params.id || this.$route.query.id) || "";

    if (!Util.isEmpty(this.orderId)) {
      this.loadInventorySheetData();
    } else {
      this.editMode = true;
      this.syncFormData();
    }
  },
  beforeUnmount() {
    if (this.retValue) {
      EventBus.emit('inventorySheetUpdated', null);
      this.retValue = null;
    }
  },

  deactivated() {
    if (this.retValue) {
      EventBus.emit('inventorySheetUpdated', null)
      this.retValue = null;
    }
  },

  computed: {
    latestUpdateInfo() {
      return (this.inventorySheet.updateor && this.inventorySheet.updateDate) ?
        (this.inventorySheet.updateor + "  " + DateUtil.getDayTitle(this.inventorySheet.updateDate)) : null;
    },

    docMaker() {
      return (this.inventorySheet.id && this.inventorySheet.docMaker && this.inventorySheet.recordDate) ?
        (this.inventorySheet.docMaker + "  " + DateUtil.getDayTitle(this.inventorySheet.recordDate)) : null
    },

    docMakerBottmBar() {
      return Engine.profile?.nickName.isEmpty
        ? Engine.profile?.userName
        : Engine.profile?.nickName;
    }
  },

  methods: {
    syncFormData() {
      this.formData = {
        docCode: this.inventorySheet.docCode,
        title: this.inventorySheet.title,
        warehouse: this.inventorySheet.warehouse,
        operateDate: this.inventorySheet.operateDate,
        operator: new Employee({ id: this.inventorySheet.operatorId, name: this.inventorySheet.operator }),
        remark: this.inventorySheet.remark,
        updator: (this.inventorySheet.updateor && this.inventorySheet.updateDate) ?
          (this.inventorySheet.updateor + "  " + DateUtil.getDayTitle(this.inventorySheet.updateDate)) : null,
        docMaker: (this.inventorySheet.id && this.inventorySheet.docMaker && this.inventorySheet.recordDate) ?
          (this.inventorySheet.docMaker + "  " + DateUtil.getDayTitle(this.inventorySheet.recordDate)) : null,
      };
    },

    fillWithFormData() {
      this.inventorySheet.title = this.formData.title;
      this.inventorySheet.warehouse = this.formData.warehouse;

      // formData.operateDate 控件变更日期会转换为字符串，这里需要转换回Date对象
      if (!(this.formData.operateDate instanceof Date)) {
        this.inventorySheet.operateDate = DateUtil.strToDate(this.formData.operateDate);
      } else {
        this.inventorySheet.operateDate = this.formData.operateDate;
      }

      this.inventorySheet.setOperator({
        operator: this.formData.operator.name,
        operatorId: this.formData.operator.id
      });
      this.inventorySheet.remark = this.formData.remark;
    },

    // 商品选择 items 类型 SubCommodityInventorySumData
    handleCommoditySelect(items) {
      if (items && items.length > 0) {
        for (let commodity of items) {
          // 检查商品是否已存在
          const exists = this.inventorySheet.commodityList.some(
            item => item.commodity.id === commodity.subCommodity.id
          );

          if (!exists) {
            let batchSheet = new CommodityBatchSheet({
              commodity: commodity.subCommodity,
              count: new CsDouble(commodity.totalInventoryCount),
              adjustCount: null, // 初始时盘点数量为空
              id: ""
            });
            this.inventorySheet.addCommodityBatch(batchSheet);
          } else {
            ElMessage.warning(`商品[${commodity.subCommodity.name}]已存在`);
          }
        }
      }
    },

    handleCopy() {
      this.inventorySheet = InventorySheet.clone(this.inventorySheet);
      this.inventorySheet.id = '';
      this.editMode = true;
      MessageUtil.showSuccessMsg("复制完成");
    },

    handlePrint() { },

    handleEdit() {
      this.editMode = true;
    },

    async handleDelete() {
      if (Util.isEmpty(this.inventorySheet.id)) {
        TabUtil.closePage();
      } else {
        try {
          await ElMessageBox.confirm("确定要删除该盘点单据吗？", "删除确认", {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          });

          this.submitting = true;

          let delResult = await this.inventoryUiAction.removeInventorySheetOrder({
            orderId: this.inventorySheet.id,
            docType: this.inventorySheet.docType
          });

          if (delResult == null) {
            this.retValue = new ActionResult({ type: ActionResultType.Del });
            MessageUtil.showSuccessMsg("删除成功");
            TabUtil.closePage();
          }
        } catch (error) {
          if (error !== 'cancel') {
            console.error("inventorySheetDetailPage handleDelete error:", error);
            ElMessage.error("删除操作失败");
          }
        } finally {
          this.submitting = false;
        }
      }
    },

    handleAddCommodity() {
      if (this.formData.warehouse == null ||
        this.formData.warehouse.id == null ||
        Util.isEmpty(this.formData.warehouse.id)) {
        MessageUtil.showWarningMsg("请先选择仓库");
        return;
      }

      this.$refs.commoditySelectDialog.open(
        this.inventorySheet.commodityList.map(item => ({
          subCommodity: item.commodity
        })),
        {
          warehouse: this.formData.warehouse
        }
      );
    },

    handleSelectionChange(selection) {
      this.selectedCommodities = selection;
    },

    handleDeleteSelectedCommodities() {
      if (this.selectedCommodities.length === 0) {
        ElMessage.warning('请至少选择一个商品进行删除');
        return;
      }

      // 删除选中的商品
      this.selectedCommodities.forEach(commodity => {
        this.inventorySheet.removeCommodityBatch(commodity);
      });

      // 清空选中
      this.selectedCommodities = [];
    },

    // 取消编辑
    handleCancel() {
      this.inventorySheet = InventorySheet.clone(this.orgInventorySheet);
      this.editMode = false;
    },

    async handleSubmit() {
      this.submitting = true;
      try {
        // 验证表单
        const validationError = this.inventorySheet.validateOrder();
        if (validationError) {
          ElMessage.error(validationError);
          return;
        }

        this.fillWithFormData();
        //console.log('提交盘点单数据', this.inventorySheet);

        const orderResult = await this.inventoryUiAction.updateOrCreateInventorySheet(this.inventorySheet, true);

        if (orderResult) {
          if (Util.isEmpty(this.inventorySheet.id)) {
            this.retValue = new ActionResult({ type: ActionResultType.New });
          } else {
            this.retValue = new ActionResult({ type: ActionResultType.UpdateCommon });
          }
        }

        if (orderResult) {
          // 刷新订单页面
          ElMessage.success("提交保存成功");
          this.orderId = orderResult.id;
          this.editMode = false;
          this.loadInventorySheetData();
        }
      } catch (error) {
        console.error('保存失败', error);
        ElMessage.error("保存失败");
      } finally {
        this.submitting = false;
      }
    },

    async loadInventorySheetData() {
      try {
        this.loading = true;
        const res = await this.inventoryUiAction.getInventorySheetDetailInfo(this.orderId);

        if (res) {
          this.inventorySheet = res;
          this.orgInventorySheet = InventorySheet.clone(res);
          this.syncFormData();
        } else {
          ElMessage.error('获取盘点单详情失败');
        }
      } catch (error) {
        console.error('加载盘点单数据失败:', error);
        ElMessage.error('加载盘点单数据失败');
      } finally {
        this.loading = false;
      }
    },

    formatCount(value, withSignal = false) {
      return Util.getCountString(value, null, { withPrePositiveNegtiveSignal: withSignal });
    },

    formatCurrency(value) {
      return Util.getFundString(value);
    },

    getAdjustBalanceClass(value) {
      if (value < 0) {
        return 'loss'; // 盘亏 - orange
      } else if (value > 0) {
        return 'gain'; // 盘盈 - green
      } else {
        return 'no-change'; // 相同 - green (柔和)
      }
    },
  }
}
</script>

<style scoped>
.inventory-sheet-detail-container {
  padding: 16px;
  padding-bottom: 80px;
  /* 留出bottom bar的空间 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-bottom: 0px;
  padding: 0 16px;
}

.title-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
}

.summary-container {
  flex: 1;
  min-width: 300px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.total-info {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.store-name {
  font-size: 12px;
  color: #606266;
}

.title-text {
  font-size: 16px;
  font-weight: bold;
}

.status-tag {
  margin-left: 12px;
}

.commodity-image {
  width: 40px;
  height: 40px;
  margin-right: 12px;
}

.remark-content {
  white-space: pre-wrap;
  word-break: break-all;
}

.info-card,
.items-card,
.other-info-card {
  margin-bottom: 16px;
  border-radius: 8px;
}

/* In the style section */
.loss {
  color: #E6A23C;
  /* 柔和的橙色 */
}

.gain {
  color: #67C23A;
  /* 柔和的绿色 */
}

.no-change {
  color: #636568; /* 柔和的灰色，表示无变化 */
  /* 白色，表示无变化 */
}
</style>